package com.hurui.xiaoming.fragment.me;

import android.Manifest;
import android.content.Context;
import android.content.Intent;
import android.graphics.drawable.BitmapDrawable;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.text.TextUtils;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.Spinner;

import com.bumptech.glide.Glide;
import com.hurui.xiaoming.R;
import com.hurui.xiaoming.activity.main.MainActivity;
import com.hurui.xiaoming.bean.Li_IsUserFinish_Result;
import com.hurui.xiaoming.fragment.BaseFragment;
import com.hurui.xiaoming.myconfig.PamaryKeys;
import com.hurui.xiaoming.utils.BitmapUtils;
import com.hurui.xiaoming.utils.ImageOnkitKat;
import com.hurui.xiaoming.utils.WriteReadSharedPrefs;
import com.squareup.picasso.Picasso;
import com.yanzhenjie.permission.AndPermission;
import com.yanzhenjie.permission.PermissionListener;
import com.yanzhenjie.permission.Rationale;
import com.yanzhenjie.permission.RationaleListener;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;


/**
 * Created by hurui on 2017/7/19.
 */

public class StudentInfoFragment extends BaseFragment implements View.OnClickListener, PermissionListener,RationaleListener{
    private final int REQUSET_CODE=10010;
    private View rootView ;
    private ImageView idCard_one,idCard_two,idCard_three,idCard_four;
    private ImageView image;
    private EditText mSchool_name_et;
    private EditText mYard_name_et,mClass_name_et,mRoom_address_et;
    private Spinner mSchool_class_spinner;
    private Context context=getContext();

    private List<String> list;
    private Li_IsUserFinish_Result.DataBean data;

    public static StudentInfoFragment newInstance( Li_IsUserFinish_Result.DataBean data ) {
        Bundle args = new Bundle();
        args.putSerializable(PamaryKeys.UI_INFO,data);
        StudentInfoFragment fragment = new StudentInfoFragment();
        fragment.setArguments(args);
        return fragment;
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        super.onCreateView(inflater, container, savedInstanceState);
        data = ((Li_IsUserFinish_Result.DataBean) getArguments().getSerializable(PamaryKeys.UI_INFO));
        list=new ArrayList<>();
        if(rootView == null){
            rootView = inflater.inflate(R.layout.fragment_student_info , null);
            initView();
            initAction();
        }
        return rootView ;
    }

    @Override
    public void initView() {
        image=new ImageView(getContext());
        rootView.findViewById(R.id.ic_close_image).setOnClickListener(this);
        rootView.findViewById(R.id.ic_close_image1).setOnClickListener(this);
        rootView.findViewById(R.id.ic_close_image2).setOnClickListener(this);
        rootView.findViewById(R.id.ic_close_image3).setOnClickListener(this);
        idCard_one = ((ImageView) rootView.findViewById(R.id.idcard_iv_1));
        rootView.findViewById(R.id.commit_btn).setOnClickListener(this);
        idCard_two = ((ImageView) rootView.findViewById(R.id.idcard_iv_2));
        idCard_three = ((ImageView) rootView.findViewById(R.id.idcard_iv_3));
        idCard_four = ((ImageView) rootView.findViewById(R.id.idcard_iv_4));

        rootView.findViewById(R.id.iDCard_positive).setOnClickListener(this);
        rootView.findViewById(R.id.iDCard_negative).setOnClickListener(this);
        rootView.findViewById(R.id.idcard_hand).setOnClickListener(this);
        rootView.findViewById(R.id.id_school).setOnClickListener(this);
        mSchool_name_et = (EditText) rootView.findViewById(R.id.school_name_et);
        mYard_name_et = (EditText) rootView.findViewById(R.id.yard_name_et);
        mClass_name_et = (EditText) rootView.findViewById(R.id.class_name_et);
        mSchool_class_spinner = (Spinner) rootView.findViewById(R.id.school_class_spinner);
        mRoom_address_et = (EditText) rootView.findViewById(R.id.room_address_et);
    }

    @Override
    public void onStart() {
        super.onStart();
        showData();
    }

    /**
     * 显示基础信息
     */
    private void showData() {
        String[] school_class = getResources().getStringArray(R.array.school_class);
        if (!TextUtils.isEmpty(data.getUi_workname())){
            mSchool_name_et.setText(data.getUi_workname());
        }
        if (!TextUtils.isEmpty(data.getUi_faculty())){
            mYard_name_et.setText(data.getUi_faculty());
        }
        if (!TextUtils.isEmpty(data.getUi_professional_class())){
            mClass_name_et.setText(data.getUi_professional_class());
        }

        if (!TextUtils.isEmpty(data.getUi_xzaddress())){
            mRoom_address_et.setText(data.getUi_xzaddress());
        }

        if (!TextUtils.isEmpty(data.getUi_url1())){
            Picasso.with(mContext).load("http://"+data.getUi_url1()).into(idCard_one);
        }
        if (!TextUtils.isEmpty(data.getUi_school_roll())){
            for (int i = 0; i < school_class.length; i++) {
                if (school_class[i].equals(data.getUi_school_roll()))
                    mSchool_class_spinner.setSelection(i);
            }
        }
        if (!TextUtils.isEmpty(data.getUi_url2())){
            Picasso.with(mContext).load("http://"+data.getUi_url2()).into(idCard_two);
        }
        if (!TextUtils.isEmpty(data.getUi_url3())){
            Picasso.with(mContext).load("http://"+data.getUi_url3()).into(idCard_three);

        }
        if (!TextUtils.isEmpty(data.getUi_url4())){
            Picasso.with(mContext).load("http://"+data.getUi_url4()).into(idCard_four);
        }

    }

    private void openImage(){
        Intent intent=new Intent("android.intent.action.GET_CONTENT");
        intent.setType("image/*");
        startActivityForResult(intent,REQUSET_CODE);
    }


    @Override
    public void initAction() {


    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if(data == null){
            return;
        }
        if (requestCode==REQUSET_CODE){
            displayImage(ImageOnkitKat.handleImageBeforeKitKat(getContext(),data));
        }
    }

    /**
     * 展示图片
     * @param path
     */
    private void displayImage(String path){

        Glide.with(getContext()).load(path).into(image);
        image.setVisibility(View.VISIBLE);
        list.add(path);

    }

    /**
     *权限成功回调
     * @param requestCode
     * @param grantPermissions
     */
    @Override
    public void onSucceed(int requestCode, @NonNull List<String> grantPermissions) {
        // 权限申请成功回调。

        switch (requestCode) {
            case 1:
                openImage();
                break;

        }
    }
    /**
     * 外部写的权限
     */
    private void  requestSDPermission() {
// 先判断是否有权限。
        if (AndPermission.hasPermission(getContext(), Manifest.permission.WRITE_EXTERNAL_STORAGE)&& AndPermission.hasPermission(getContext(),Manifest.permission.READ_EXTERNAL_STORAGE)&&
                AndPermission.hasPermission(getContext(),Manifest.permission.CAMERA)) {
            // 有权限，直接do anything.startCamera9
            openImage();

        } else {
            // 申请权限。
            onToast("没有权限");
            AndPermission.with(this)
                    .requestCode(1)
                    .permission(Manifest.permission.WRITE_EXTERNAL_STORAGE,Manifest.permission.READ_EXTERNAL_STORAGE,Manifest.permission.CAMERA)
                    .rationale(this)
                    .callback(this)
                    .start();
        }
    }

    /**
     * 权限拒绝
     * @param requestCode
     * @param deniedPermissions
     */
    @Override
    public void onFailed(int requestCode, @NonNull List<String> deniedPermissions) {
          onToast("权限拒绝");
        if (AndPermission.hasAlwaysDeniedPermission(getActivity(),deniedPermissions)){
            AndPermission.defaultSettingDialog(getActivity(),200).
                    setTitle("权限申请失败")
                    .setMessage("我们需要的一些权限被您拒绝或者系统发生错误申请失败，请您到设置页面手动授权，否则功能无法正常使用！")
                    .setPositiveButton("好，去设置")
                    .show();
        }
    }

    @Override
    public void showRequestPermissionRationale(int requestCode, Rationale rationale) {
                AndPermission.rationaleDialog(mContext,rationale).show();
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()){
            case R.id.ic_close_image:
                if (idCard_one.getVisibility()==View.VISIBLE){
                    idCard_one.setVisibility(View.GONE);
                    list.remove(0);
                }
                break;
            case R.id.ic_close_image1:
                if (idCard_two.getVisibility()==View.VISIBLE){
                    idCard_two.setVisibility(View.GONE);
                    list.remove(1);
                }
                break;
            case R.id.ic_close_image2:
                if (idCard_three.getVisibility()==View.VISIBLE){
                    idCard_three.setVisibility(View.GONE);
                    list.remove(2);
                }
                break;
            case R.id.ic_close_image3:
                if (idCard_four.getVisibility()==View.VISIBLE){
                    idCard_four.setVisibility(View.GONE);
                    list.remove(3);
                }
                break;
            case R.id.iDCard_positive:
               image=idCard_one;
                requestSDPermission();
                break;
            case R.id.iDCard_negative:
                image=idCard_two;
                requestSDPermission();
                break;
            case R.id.idcard_hand:
                image=idCard_three;
                requestSDPermission();
                break;
            case R.id.id_school:
                image=idCard_four;
                requestSDPermission();
                break;
            case R.id.commit_btn:
                commitID();

                break;

        }
    }

    private void commitID() {
       Map<String,Object> map=  new HashMap<>();
        if (TextUtils.isEmpty(mSchool_name_et.getText().toString())){
            onToast("请输入学校名称");
            return;
        }
        if (TextUtils.isEmpty(mYard_name_et.getText().toString())){
            onToast("请输入你的院系");
            return;
        }
        if (TextUtils.isEmpty(mClass_name_et.getText().toString())){
            onToast("请输入您的专业班级");
            return;
        }
        if (TextUtils.isEmpty(mRoom_address_et.getText().toString())){
            onToast("请输入你的寝室地址");
            return;
        }

       /*if (list.size()<4){
           onToast("请上传证件照片");
           return;
       }*/
        map.put(PamaryKeys.UI_ID, WriteReadSharedPrefs.readUserID(mContext)+"");
        map.put("ui_yhtype","1");
        map.put("ui_xzaddress",mRoom_address_et.getText().toString());
        map.put("ui_school_roll",mSchool_class_spinner.getSelectedItem().toString());
        map.put("ui_workname",mSchool_name_et.getText().toString());
        map.put("ui_faculty",mYard_name_et.getText().toString());
        map.put("ui_professional_class",mClass_name_et.getText().toString());
        map.put("ui_url1","data:image/png;base64,"+BitmapUtils.Bitmap2StrByBase64((((BitmapDrawable) idCard_one.getDrawable()).getBitmap())));
        map.put("ui_url2","data:image/png;base64,"+BitmapUtils.Bitmap2StrByBase64(((BitmapDrawable) idCard_two.getDrawable()).getBitmap()));
        map.put("ui_url3","data:image/png;base64,"+BitmapUtils.Bitmap2StrByBase64(((BitmapDrawable) idCard_three.getDrawable()).getBitmap()));
        map.put("ui_url4","data:image/png;base64,"+BitmapUtils.Bitmap2StrByBase64(((BitmapDrawable) idCard_four.getDrawable()).getBitmap()));

        apiSevice.onHttp_Info2(map).enqueue(new Callback<Li_IsUserFinish_Result>() {
            @Override
            public void onResponse(Call<Li_IsUserFinish_Result> call, Response<Li_IsUserFinish_Result> response) {
                    if (response.body().getStatus().equals("success")){
                        onToast("身份信息已提交");
                        Log.e("wwww", "onResponse: "+response.body().getData().toString());

                        Intent intent = new Intent(getContext(), MainActivity.class);
//                      //  intent.putExtra(PamaryKeys.UI_ID,1);
                        startActivity(intent);
                        onFinish();

                    }else {
                        onToast("请输入正确的信息");
                    }
            }

            @Override
            public void onFailure(Call<Li_IsUserFinish_Result> call, Throwable t) {
                Log.e("122ee", "onFailure: "+t.getMessage() );
            }
        });
    }
}
